package com.dubbo.auth.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

@Slf4j
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private AuthLoginService authLoginService;

//    {
//        //设置用于匹配密码的CredentialsMatcher
//        HashedCredentialsMatcher hashMatcher = new HashedCredentialsMatcher();
//        hashMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
//        hashMatcher.setStoredCredentialsHexEncoded(false);
//        hashMatcher.setHashIterations(1024);
//        this.setCredentialsMatcher(hashMatcher);
//    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String name = (String) principalCollection.getPrimaryPrincipal();
        AuthUserInfo authUserInfo = authLoginService.getAuthUserInfoByName(name);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if(null!=authUserInfo){
            authUserInfo.getRole().stream().forEach(e->{
                simpleAuthorizationInfo.addRole(e);
            });
            authUserInfo.getPermission().stream().forEach(e->{
                simpleAuthorizationInfo.addStringPermission(e);
            });
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 获取用户信息
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
            return null;
        }
        String name = authenticationToken.getPrincipal().toString();
        AuthUserInfo authUserInfoByName = authLoginService.getAuthUserInfoByName(name);
        if(null==authUserInfoByName){
            throw new AuthenticationException("登录用户不存在");
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, authUserInfoByName.getPassword().toString(), getName());
        if (authUserInfoByName.getSalt() != null) {
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(authUserInfoByName.getSalt()));
        }
        return simpleAuthenticationInfo;
    }

}
